﻿<cfsilent>
	<cfsetting requesttimeout="900">

	<cfset this.DSN = "Pathfinder">

	<cfif StructKeyExists(form,"iterations")>
		<cfset variables.iterations = form.iterations>
	<cfelseif StructKeyExists(URL,"iterations")>
		<cfset variables.iterations = url.iterations>
	<cfelse>
		<cfset variables.iterations = 5000>
	</cfif>
	<cfif StructKeyExists(form,"itemtypeid")>
		<cfset variables.itemtypeid = form.itemtypeid>
	<cfelseif StructKeyExists(URL,"itemtypeid")>
		<cfset variables.itemtypeid = url.itemtypeid>
	<cfelse>
		<cfset variables.itemtypeid = 1>
	</cfif>
</cfsilent><cfmodule template="../_header.cfm">
</cfmodule>

<form method="post">
	<select name="itemtypeid">
		<option value="1"<cfif variables.itemtypeid eq 1> selected="selected"</cfif>>minor</option>
		<option value="2"<cfif variables.itemtypeid eq 2> selected="selected"</cfif>>medium</option>
		<option value="3"<cfif variables.itemtypeid eq 3> selected="selected"</cfif>>major</option>
	</select>
	<br/>
	<input type="text" name="iterations" value="<cfoutput>#variables.iterations#</cfoutput>" size="8" />
	<br/>
	<button>get it</button>
</form>

<cfif structKeyExists(form,"fieldnames")>
	<cfset variables.CollatedItemTypes = {
		1 = 0,
		2 = 0,
		3 = 0,
		4 = 0,
		5 = 0,
		6 = 0,
		7 = 0,
		8 = 0,
		9 = 0,
		10 = 0,
		11 = 0,
		12 = 0,
		13 = 0,
		14 = 0,
		15 = 0,
		16 = 0,
		17 = 0
	}>
	[starting...]<br/>

	<cftry>

	<cfloop from="1" to="#variables.iterations#" index="variabes.i">

		<cfquery name="local.GetItemType" datasource="#this.DSN#">
			SELECT ic.ItemTypeID, ic.weighted
			FROM itemcategories ic
			join ItemTypes it on it.ID = ic.ItemTypeID
			where ic.id = #variables.itemtypeid# and ic.weighted > 0
			ORDER BY -LOG(1 - rand()) / ic.weighted asc
			LIMIT 1
		</cfquery>

		<cfset variables.CollatedItemTypes[local.GetItemType.ItemTypeID]++>
	</cfloop>
	<cfcatch>
		<cfdump var="#cfcatch#">
	</cfcatch>
	</cftry>
	<cfoutput>
		<table>
			<thead>
				<tr>
					<th>Type ID</th>
					<th>Qty</th>
					<th>%</th>
				</tr>
					<cfloop list="#ListSort(StructKeyList(variables.CollatedItemTypes), "numeric", "ASC")#" index="key">
	<!---			<cfloop collection="#variables.CollatedItemTypes#" item="key">--->
					<tr>
						<td>#key#</td>
						<td>#variables.CollatedItemTypes[key]#</td>
						<td>#variables.CollatedItemTypes[key] / variables.iterations * 100#</td>
					</tr>
				</cfloop>
			</thead>
		</table>
	</cfoutput>
	[done...]
</cfif>
<cfmodule template="../_footer.cfm">
</cfmodule>